package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminLoginMapper;
import com.heima.admin.service.AdminLoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Psycho
 * @create 2022-05-02-9:56
 */
@Service
@Slf4j
public class AdminLoginServiceImpl extends ServiceImpl<AdminLoginMapper, AdUser> implements AdminLoginService {
    /**
     * 后台管理系统的登入
     *
     * @param params
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto params) {
        Map<String,Object> map = new HashMap<>();
        //1.正常登入
        //1.1判断是否输入了账号密码
        if(!StringUtils.isBlank(params.getName()) && !StringUtils.isBlank(params.getPassword())){
            //1.2查询是否有该用户
            AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, params.getName()));
            if(user ==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //1.3对用户输入的密码进行加盐处理然后再MD5加密，最后用加密串对数据库的密码进行校验
            String salt = user.getSalt();
            String pswd = params.getPassword();
            pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
            if(!pswd.equals(user.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.4登入成功后生成唯一标识JWT
            String token = AppJwtUtil.getToken(user.getId().longValue());
            //1.5将数据返回给前端
            map.put("token",token);
            //在封装对象之前把密码跟盐置空
            user.setPassword("");
            user.setSalt("");
            map.put("user",user);
            return ResponseResult.okResult(map);
        }else {
            //2.游客登入
            String token = AppJwtUtil.getToken(0L);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
